﻿using IdentityModel.Client;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace IdentityServer4Client.Password
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                RequestTestAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("Hello World!");
            Console.ReadKey();
        }

        private static async Task RequestTestAsync()
        {
            var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }
            var tokenClient = new TokenClient(disco.TokenEndpoint, "passwordClient", "p@ssw0rd");
            var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync("admin", "p@ssw0rd");
            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }

            var httpClient = new HttpClient();
            httpClient.SetBearerToken(tokenResponse.AccessToken);
            var response = await httpClient.GetAsync("http://localhost:5001/api/values/get");
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
                return;
            }
            var content=await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
    }
}
